/**
 * @Author: Kirito
 * @Date: 2020/12/28
 */
package core

import "errors"

type Event struct {
	es map[string][]func(interface{}) error
	as map[string]bool
}

func (e *Event) On(name string, async bool, f ...func(interface{}) error) {
	if e.es == nil {
		e.es = make(map[string][]func(interface{}) error)
	}
	if e.as == nil {
		e.as = make(map[string]bool)
	}

	e.as[name] = async
	e.es[name] = f
}

func (e Event) Emit(name string, v interface{}) error {
	f, exist := e.es[name]
	if !exist {
		return errors.New("事件不存在")
	}

	for i := range f {
		_f := f[i]
		if e.as[name] {
			go _f(v)
		} else {
			err := _f(v)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
